package com.aaa.controller;

import cn.hutool.core.util.ObjectUtil;
import com.aaa.entity.Result;
import com.aaa.entity.system.Userinfo;
import com.aaa.service.system.MenuService;
import com.aaa.service.system.UserinfoService;
import com.aaa.utils.MyTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author ：Teacher陈（86521760@qq.com）
 * @date ：Created in 2022/8/29 10:55
 * @description：登录控制器
 * @modified By：
 * @version: 1.0
 */
@RestController
public class LoginController extends BaseController {
    @Autowired
    UserinfoService userinfoService;
    @Autowired
    MenuService menuService;

    @RequestMapping(method = RequestMethod.POST, value = "login.do")
    public Result login(@RequestBody Userinfo userinfo, HttpSession session) {
        //根据用户中的用户名和密码进行合法性校验
        Userinfo newUserinfo = userinfoService.queryUserEntityByName(userinfo.getUsername());
        if (ObjectUtil.isEmpty(newUserinfo)) {
            //用户不存在
            return fail("用户" + userinfo.getUsername() + "不存在");
        } else {
            //用户存在,
            // 1、根据用户将用户的盐值和密文查询出来
            String salt = newUserinfo.getSalt();
            //数据库的密文
            String password = newUserinfo.getPassword();
            // 2、将明文密码加密之后跟第一步的密文对比，一致就是登录成功
            String makePasswordSalt = MyTools.makePasswordSalt(userinfo.getPassword(), salt);
            if (makePasswordSalt.equals(password)) {
                //登录成功，根据用户名，查询对应的所有的菜单
                Map<String, Object> menuListMap = menuService.queryMenuByUsername(userinfo.getUsername());
                System.out.println(menuListMap);
                session.setAttribute("menuListMap", menuListMap);
                session.setAttribute("user", newUserinfo);
                return success("登录成功");
            } else {
                return fail("密码错误");
            }
        }
    }

    @RequestMapping("logout.do")
    public ModelAndView logout(ModelAndView modelAndView, HttpSession session) {
        //注销,需要销毁session
        session.invalidate();
        //跳转到登录页面
        modelAndView.setViewName("../login");
        return modelAndView;
    }
}
